package actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import donnees.Commande;

import metier.client.MetierFactory;
import metier.interfaces.IRemoteHistorique;

public class ActionHistorique implements IAction {

	@Override
	public String execute(HttpServletRequest req) throws Exception {

		String retour = "historique.jsp";

		// récupération de la session
		HttpSession session = req.getSession();

		// récupération du metier
		IRemoteHistorique metier = (IRemoteHistorique) MetierFactory
				.getInstance().getMetier("Historique");

		/* tester si utilisateur connecté */

		if (session.getAttribute("id_client") == null) {
			retour = "connexion.jsp";
			session.setAttribute("provenance", "historique");
		} else {

			/* Récuperer les commandes */
			ArrayList<Commande> lesCommandes = metier
					.getCommandesClient((Integer) session
							.getAttribute("id_client"));

			HashMap<Integer, ArrayList<String>> lesLignesCommande = new HashMap<Integer, ArrayList<String>>();

			/* Récuperer les lignes formattées */
			if (lesCommandes != null) {

				for (Commande cmd : lesCommandes) {
					lesLignesCommande.put(cmd.getIdCommande(),
							metier.getLignesDeCommande(cmd.getIdCommande()));
				}
			}

			req.setAttribute("commandes", lesCommandes);
			req.setAttribute("lignescommandes", lesLignesCommande);

			session.setAttribute("lignescommandes", lesLignesCommande);

			/* Traiter changement adresse */

			req.setAttribute("modnom", "");
			req.setAttribute("modprenom", "");
			req.setAttribute("modnumero", "");
			req.setAttribute("modadresse", "");
			req.setAttribute("modcodepostal", "");
			req.setAttribute("modville", "");

			if (req.getParameter("modifier") != null) {

				boolean idclient = metier.changerAdresse(
						(Integer) session.getAttribute("id_client"),
						req.getParameter("modnom"),
						req.getParameter("modprenom"),
						req.getParameter("modnumero"),
						req.getParameter("modadresse"),
						req.getParameter("modcodepostal"),
						req.getParameter("modville"));

				if (!idclient) {
					req.setAttribute("erreur_modif", "Champ(s) invalides.");
					req.setAttribute("modnom", req.getParameter("modnom"));
					req.setAttribute("modprenom", req.getParameter("modprenom"));
					req.setAttribute("modnumero", req.getParameter("modnumero"));
					req.setAttribute("modadresse",
							req.getParameter("modadresse"));
					req.setAttribute("modcodepostal",
							req.getParameter("modcodepostal"));
					req.setAttribute("modville", req.getParameter("modville"));
				}
			}

			/* Récupérer adresse */

			req.setAttribute("client", metier.getClient((Integer) session
					.getAttribute("id_client")));
		}

		return retour;
	}

}
